#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Maven安装器命令行版本
用于测试核心功能
"""

import platform
import requests
import os
import threading
import zipfile
import tarfile
import shutil
import warnings

# 忽略SSL警告
warnings.filterwarnings('ignore', message='urllib3 v2 only supports OpenSSL 1.1.1+')

def detect_os():
    """检测操作系统信息"""
    system = platform.system().lower()
    machine = platform.machine().lower()
    
    os_info = {
        'system': system,
        'machine': machine,
        'platform': platform.platform(),
        'version': platform.version()
    }
    
    # 确定下载文件扩展名
    if system == 'windows':
        os_info['extension'] = 'zip'
        os_info['binary_name'] = 'mvn.cmd'
    elif system == 'darwin':  # macOS
        os_info['extension'] = 'tar.gz'
        os_info['binary_name'] = 'mvn'
    else:  # Linux
        os_info['extension'] = 'tar.gz'
        os_info['binary_name'] = 'mvn'
    
    return os_info

def get_maven_versions():
    """获取Maven版本列表"""
    try:
        print("正在获取Maven版本列表...")
        
        # 使用Maven官方API获取版本列表
        url = "https://repo1.maven.org/maven2/org/apache/maven/apache-maven/maven-metadata.xml"
        response = requests.get(url, timeout=10)
        
        if response.status_code == 200:
            # 解析XML获取版本信息
            import xml.etree.ElementTree as ET
            root = ET.fromstring(response.text)
            
            versions = []
            for version in root.findall('.//version'):
                if version.text and not version.text.endswith('-SNAPSHOT'):
                    versions.append(version.text)
            
            # 按版本号排序（降序）
            def version_key(version):
                try:
                    # 处理版本号，只取数字部分进行排序
                    parts = version.split('.')
                    key_parts = []
                    for part in parts:
                        # 提取数字部分
                        num_part = ''
                        for char in part:
                            if char.isdigit():
                                num_part += char
                            else:
                                break
                        key_parts.append(int(num_part) if num_part else 0)
                    return key_parts
                except:
                    return [0]  # 如果解析失败，放在最前面
            
            versions.sort(key=version_key, reverse=True)
            
            return versions[:20]  # 只返回最新的20个版本
            
        else:
            print(f"获取版本列表失败: HTTP {response.status_code}")
            return []
            
    except Exception as e:
        print(f"获取版本列表时出错: {str(e)}")
        return []

def get_download_url(version, os_info):
    """获取下载URL"""
    base_url = "https://archive.apache.org/dist/maven/maven-3"
    filename = f"apache-maven-{version}-bin.{os_info['extension']}"
    return f"{base_url}/{version}/binaries/{filename}"

def download_file(url, filepath):
    """下载文件"""
    print(f"开始下载: {url}")
    response = requests.get(url, stream=True, timeout=30)
    response.raise_for_status()
    
    total_size = int(response.headers.get('content-length', 0))
    downloaded_size = 0
    
    with open(filepath, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)
            downloaded_size += len(chunk)
            
            if total_size > 0:
                progress = (downloaded_size / total_size) * 100
                print(f"\r下载进度: {progress:.1f}% ({downloaded_size//1024//1024}MB / {total_size//1024//1024}MB)", end='', flush=True)
    
    print("\n下载完成!")

def extract_file(filepath, extract_dir):
    """解压文件"""
    print("开始解压...")
    if filepath.endswith('.zip'):
        with zipfile.ZipFile(filepath, 'r') as zip_ref:
            zip_ref.extractall(extract_dir)
    elif filepath.endswith('.tar.gz'):
        with tarfile.open(filepath, 'r:gz') as tar_ref:
            tar_ref.extractall(extract_dir)
    print("解压完成!")

def install_maven(version, install_dir):
    """安装Maven"""
    try:
        os_info = detect_os()
        
        print(f"开始安装Maven {version}")
        print(f"操作系统: {os_info['platform']}")
        print(f"安装目录: {install_dir}")
        
        # 创建安装目录
        os.makedirs(install_dir, exist_ok=True)
        
        # 下载Maven
        download_url = get_download_url(version, os_info)
        print(f"下载URL: {download_url}")
        
        # 下载文件
        filename = f"apache-maven-{version}-bin.{os_info['extension']}"
        filepath = os.path.join(install_dir, filename)
        
        download_file(download_url, filepath)
        
        # 解压文件
        extract_file(filepath, install_dir)
        
        # 移动文件到最终位置
        extracted_dir = os.path.join(install_dir, f"apache-maven-{version}")
        final_dir = os.path.join(install_dir, "maven")
        
        if os.path.exists(final_dir):
            shutil.rmtree(final_dir)
        shutil.move(extracted_dir, final_dir)
        
        # 清理下载文件
        os.remove(filepath)
        
        print("Maven安装完成!")
        
        # 显示环境变量配置信息
        bin_path = os.path.join(final_dir, "bin")
        
        print(f"""
安装路径: {final_dir}

请手动配置环境变量：

macOS/Linux:
export MAVEN_HOME={final_dir}
export PATH=$PATH:{bin_path}

或者将以下内容添加到 ~/.bashrc 或 ~/.zshrc:
export MAVEN_HOME={final_dir}
export PATH=$PATH:{bin_path}

配置完成后，请重新打开终端并运行 'mvn --version' 验证安装。
""")
        
    except Exception as e:
        print(f"安装失败: {str(e)}")

def main():
    print("=== Maven安装器 (命令行版本) ===")
    
    # 检测操作系统
    os_info = detect_os()
    print(f"检测到操作系统: {os_info['platform']}")
    print(f"系统架构: {os_info['machine']}")
    print()
    
    # 获取版本列表
    versions = get_maven_versions()
    if not versions:
        print("无法获取Maven版本列表，退出程序")
        return
    
    print(f"找到 {len(versions)} 个可用版本:")
    for i, version in enumerate(versions[:10], 1):  # 只显示前10个
        print(f"{i}. Maven {version}")
    print()
    
    # 选择版本
    try:
        choice = input("请选择要安装的版本 (输入序号): ")
        choice_idx = int(choice) - 1
        if 0 <= choice_idx < len(versions):
            selected_version = versions[choice_idx]
        else:
            print("无效选择，使用最新版本")
            selected_version = versions[0]
    except ValueError:
        print("无效输入，使用最新版本")
        selected_version = versions[0]
    
    print(f"选择的版本: Maven {selected_version}")
    
    # 选择安装目录
    default_path = "/usr/local/maven" if os_info['system'] != 'windows' else "C:\\Program Files\\Maven"
    install_path = input(f"请输入安装目录 (默认: {default_path}): ").strip()
    if not install_path:
        install_path = default_path
    
    print(f"安装目录: {install_path}")
    print()
    
    # 确认安装
    confirm = input("确认开始安装? (y/N): ").strip().lower()
    if confirm in ['y', 'yes']:
        install_maven(selected_version, install_path)
    else:
        print("安装已取消")

if __name__ == "__main__":
    main()
